package com.dashboard.sync.pool;

import cn.hutool.core.collection.CollectionUtil;
import com.dashboard.common.utils.DateUtils;
import com.dashboard.entity.WarningJob;
import com.dashboard.event.PublishSpringEvent;
import com.dashboard.event.entity.HotListSpringEventEntity;
import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author xuxiao
 */
@Slf4j
public class HotListPoolExecutor {

    private  volatile AtomicInteger atomicInteger = new AtomicInteger(1);

    private volatile CopyOnWriteArrayList<WarningJob> warningJobs = new CopyOnWriteArrayList<>();

    private static AtomicBoolean flag = new AtomicBoolean(true);

    ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2);

    private volatile Integer minTaskExecuteTime ;
    /**
     * 预警启动时间  每天晚上8点触发
     */
    private String runTime="16:38:00";

    /**
     * 关闭任务
     */
    public void showdown()
    {
        flag.getAndSet(false);
        scheduled.shutdown();
    }

    /**
     * 获取 所有正在跑的热榜任务
     * @return 正在跑的热榜任务
     */
    public  CopyOnWriteArrayList<WarningJob> getRunTimeJobs()
    {
        return  warningJobs;
    }

    /**
     * 添加一个热榜任务
     * @param warningJob 任务
     * @return 添加成功
     */
    public boolean addHotListJob(WarningJob warningJob){
        while (flag.get()){
            atomicInteger.incrementAndGet();
            try {
                return this.warningJobs.addIfAbsent(warningJob);
            } catch (Exception e) {
                log.error("添加数据到队列中被打断了");
                continue;
            }finally {
                this.minTaskExecuteTime =  setMinTaskExecuteTime(this.warningJobs);
            }
        }
        return false;
    }

    /**
     * 消费所有热榜任务
     */
    public void consumerAllHotJobs(){
        while (!flag.get()){
            scheduled.shutdown();
        }
        try {
            //触发时间
            long initDelay = DateUtils.getTimeMillis(runTime) - System.currentTimeMillis();
            long oneDay = 24 * 60 * 60 * 1000;
            initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
            scheduled.scheduleAtFixedRate(new MyScheduleThread(), 0, this.minTaskExecuteTime, TimeUnit.MILLISECONDS);
        } finally {
        }
    }

    private class MyScheduleThread implements Runnable{

        @Override
        public void run() {
            if(CollectionUtil.isNotEmpty(warningJobs)){
                // 在此处用一个 Tread.sleep(目标耗时既可) TODO
                System.out.println("取出数据,当前队列数量："+warningJobs.size()+"每次等待："+minTaskExecuteTime);
                HotListSpringEventEntity hotListSpringEventEntity = new HotListSpringEventEntity(HotListPoolExecutor.this.warningJobs);
                PublishSpringEvent.publishHotListEvent(hotListSpringEventEntity);

                System.out.println("=========================================");
            }
        }
    }

    private static synchronized Integer setMinTaskExecuteTime(List<WarningJob> list){
        if(CollectionUtil.isEmpty(list)){
            return Integer.MAX_VALUE;
        }
        return list.stream().map(WarningJob::getMinTriggerTime).min(Comparator.comparingInt(item->item)).get();
    }

}
